<template>
    <div>
      <h1>基线矫正处理</h1>
      <el-form :model="formData">
        <el-form-item label="多项式阶数">
          <el-input v-model="formData.polyorder" type="number"></el-input>
        </el-form-item>
      </el-form>
      <file-upload @data-extracted="handleDataExtracted"></file-upload>
      <el-button type="primary" @click="processData" :disabled="!uploadedData">开始处理</el-button>
      <el-progress v-if="loading" :percentage="progress"></el-progress>
      <line-chart 
        v-if="uploadedData && uploadedData.wavelengths.length && uploadedData.intensities.length"
        :x="uploadedData.wavelengths" 
        :y="uploadedData.intensities" 
        :title="uploadedData.fileName + ' (原始数据)'">
      </line-chart>
      <line-chart 
        v-if="processedData" 
        :x="processedData.wavelengths" 
        :y="processedData.intensities" 
        :title="uploadedData.fileName + ' (处理后数据)'">
      </line-chart>
    </div>
  </template>
  
  <script>
  import FileUpload from '@/components/FileUpload.vue';
  import LineChart from '@/components/LineChart.vue';
  import { create, all } from 'mathjs';
  
  const math = create(all);
  
  export default {
    components: {
      FileUpload,
      LineChart
    },
    data() {
      return {
        formData: {
          polyorder: 2 // 默认多项式阶数
        },
        uploadedData: null,
        loading: false,
        progress: 0,
        processedData: null
      };
    },
    methods: {
      handleDataExtracted(data) {
        this.uploadedData = data;
      },
      processData() {
        if (!this.uploadedData) return;
  
        this.loading = true;
        this.progress = 0;
  
        const { wavelengths, intensities } = this.uploadedData;
  
        // 前端进行基线矫正
        const correctedIntensities = this.baselineCorrection(wavelengths, intensities, this.formData.polyorder);
  
        this.processedData = {
          wavelengths: wavelengths,
          intensities: correctedIntensities
        };
  
        this.loading = false;
      },
      baselineCorrection(wavelengths, intensities, polyorder) {
        // 多项式拟合
        const coefficients = math.polyfit(wavelengths, intensities, polyorder);
        // 基线拟合值
        const baseline = wavelengths.map(x => math.evaluate(math.poly(coefficients).toString(), { x }));
  
        // 矫正后的数据
        return intensities.map((y, i) => y - baseline[i]);
      }
    }
  };
  </script>
  
  <style scoped>
  /* 添加样式以适应页面设计 */
  </style>
  